﻿using System.Data;
using System.Data.Entity.Core.Common.CommandTrees.ExpressionBuilder;
using System.Diagnostics;

namespace dkGameTool
{


    public partial class mainFrm : Form
    {
        private DataTable dtDevice;
        private DataTable dtSkill;
        private DataTable dtChallenge;
        private Dictionary<string, Device> DeviceStatus = new Dictionary<string, Device>();
        private Dictionary<string, int> EngineStatus = new Dictionary<string, int>();
        public mainFrm()
        {
            InitializeComponent();
            dtChallenge = new DataTable();
            dtSkill = new DataTable();
            dtDevice = new DataTable();
            DataColumn dcol = dtDevice.Columns.Add();
            dcol.ColumnName = "deviceId";

            dgvDevice.DataSource = dtDevice;


            load_Device();

            timer1_Tick(this, EventArgs.Empty);

            loadData();

            //KillGameTool();

            timer1.Start();


        }

        ~mainFrm()
        {
            KillGameTool();
        }


        private bool StartGameTool(string path, string deviceId)
        {
            ProcessStartInfo startInfo = new ProcessStartInfo();
            startInfo.FileName = "powershell.exe";
            string sdir = string.Format("./script/{0}", path);

            startInfo.Arguments = string.Format("./start.bat {0} {1}", sdir, deviceId); // 注意使用双引号转义  
            startInfo.RedirectStandardOutput = false; // 如果你需要捕获输出  
            startInfo.UseShellExecute = true; // 如果你需要捕获输出，则必须设置为false  
            startInfo.WindowStyle = ProcessWindowStyle.Hidden;

            EngineStatus[path] = 1;
            using (Process process = Process.Start(startInfo))
            {
                if (process != null)
                {
                    EngineStatus[path] = 1;
                    return true;

                }
                else
                {
                    EngineStatus[path] = 0;
                    return false;
                   
                }
            }
        }

        private void CutTool(string deviceId)
        {
            ProcessStartInfo startInfo = new ProcessStartInfo();
            startInfo.FileName = "powershell.exe";
            string sdir = "./CutImgTool.exe";

            startInfo.Arguments = string.Format("./start_img.bat {0} {1}", sdir, deviceId); // 注意使用双引号转义  
            startInfo.RedirectStandardOutput = false; // 如果你需要捕获输出  
            startInfo.UseShellExecute = true; // 如果你需要捕获输出，则必须设置为false  

            using (Process process = Process.Start(startInfo))
            {

            }
        }

        bool IsProcessRunning(string processName)
        {
            Process[] processes = Process.GetProcessesByName("gameTool");

            foreach (Process process in processes)
            {
                try
                {
                    string processPath = process.MainModule.FileName;
                    bool contains = processPath.Contains(processName+ "\\gameTool");
                    if (contains)
                    {
                        return true;
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                }

            }

            return false;
        }

        private void KillGameTool()
        {
            ProcessStartInfo startInfo = new ProcessStartInfo();
            startInfo.FileName = "powershell.exe";
            startInfo.Arguments = $"taskkill /F /IM gameTool.exe"; // 注意使用双引号转义  
            startInfo.RedirectStandardOutput = true; // 如果你需要捕获输出  
            startInfo.UseShellExecute = false; // 如果你需要捕获输出，则必须设置为false  

            using (Process process = Process.Start(startInfo))
            {
                if (process != null)
                {
                    // 读取输出（如果RedirectStandardOutput为true）  
                    using (StreamReader reader = process.StandardOutput)
                    {
                        string result = reader.ReadToEnd();
                        Console.Write(result);
                    }

                    // 等待进程结束  
                    process.WaitForExit();
                }
            }
        }

        private void load_Device()
        {
            ProcessStartInfo startInfo = new ProcessStartInfo();
            startInfo.FileName = "powershell.exe";
            startInfo.Arguments = $"./adb.exe devices"; // 注意使用双引号转义  
            startInfo.RedirectStandardOutput = true; // 如果你需要捕获输出  
            startInfo.UseShellExecute = false; // 如果你需要捕获输出，则必须设置为false  

            using (Process process = Process.Start(startInfo))
            {
                if (process != null)
                {
                    // 读取输出（如果RedirectStandardOutput为true）  
                    using (StreamReader reader = process.StandardOutput)
                    {
                        string result = reader.ReadToEnd();
                        Console.Write(result);

                        string[] devices = result.Split("\n");
                        if (devices.Length == 0)
                        {
                            return;
                        }

                        for (int i = 1; i < devices.Length; i++)
                        {
                            if (devices[i].Contains("device"))
                            {
                                string s = devices[i].Replace("\t", "");

                                s = s.Replace("device", "");
                                s = s.Replace("\r", "");
                                s = s.Replace(" ", "");
                                string[] rs = { s };
                                dtDevice.Rows.Add(rs);
                                Device device = new Device(s);
                                DeviceStatus.Add(s, device);
                            }
                        }
                        Console.WriteLine(devices);
                    }

                    // 等待进程结束  
                    process.WaitForExit();
                }
            }

        }

        private void label1_Click(object sender, EventArgs e)
        {

        }

        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }

        private void dataGridView1_CellContentClick_1(object sender, DataGridViewCellEventArgs e)
        {

        }

        private void button10_Click(object sender, EventArgs e)
        {
            DataGridViewRow currRow = dgvDevice.CurrentRow;
            if (currRow != null)
            {
                System.Console.WriteLine(currRow.Cells[0].Value);
                if (currRow.Cells[0].Value == null)
                {
                    return;
                }
                string deviceId = currRow.Cells[0].Value.ToString();
                SkillForm skillForm = new SkillForm(0, deviceId);
                skillForm.ShowDialog();

                this.loadData();

            }

        }

        private void button13_Click(object sender, EventArgs e)
        {


            DataGridViewRow currRow = dgvDevice.CurrentRow;
            if (currRow != null)
            {
                System.Console.WriteLine(currRow.Cells[0].Value);
                if (currRow.Cells[0].Value == null)
                {
                    return;
                }
                string deviceId = currRow.Cells[0].Value.ToString();
                SkillForm skillForm = new SkillForm(1, deviceId);
                skillForm.ShowDialog();

                this.loadData();

            }


        }

        private string getCurrDeviceId()
        {
            DataGridViewRow currRow = dgvDevice.CurrentRow;
            if (currRow != null)
            {
                System.Console.WriteLine(currRow.Cells[0].Value);
                if (currRow.Cells[0].Value == null)
                {
                    return "";
                }
                string deviceId = currRow.Cells[0].Value.ToString();
                return deviceId;
            }
            return "";
        }
        private void loadData()
        {
            DataGridViewRow currRow = dgvDevice.CurrentRow;
            if (currRow != null)
            {
                System.Console.WriteLine(currRow.Cells[0].Value);
                if (currRow.Cells[0].Value == null)
                {
                    return;
                }
                string deviceId = currRow.Cells[0].Value.ToString();
                dtSkill = DataBaseManager.GetInstance.getDataChooseSkill(deviceId);
                dgvSkill.DataSource = dtSkill;

                dtChallenge = DataBaseManager.GetInstance.getDataChooseChallenge(deviceId);
                dgvChallenge.DataSource = dtChallenge;

            }
        }

        private void dgvDevice_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            this.loadData();
            label3.Text = string.Format("在这里设置设备：{0} 相关参数！", getCurrDeviceId());
        }

        private void button12_Click(object sender, EventArgs e)
        {
            //DataGridViewRow currRow = dgvDevice.CurrentRow;
            //if (currRow != null)
            //{
            //    System.Console.WriteLine(currRow.Cells[0].Value);
            //    if (currRow.Cells[0].Value == null)
            //    {
            //        return;
            //    }
            //    string deviceId = currRow.Cells[0].Value.ToString();
            //    dtSkill = DataBaseManager.GetInstance.getDataChooseSkill(deviceId);
            //    dgvSkill.DataSource = dtSkill;

            //    dtChallenge = DataBaseManager.GetInstance.getDataChooseChallenge(deviceId);
            //    dgvChallenge.DataSource = dtChallenge;

            //}


            



            string engine = "";

            // 查看是否有空闲的引擎
            for (int i = 1; i <= 5; i++)
            {
                string engineName = string.Format("game0{0}", i);
                if (!IsProcessRunning(engineName))
                {
                    engine = engineName;
                    break;
                }
            }

            if (string.IsNullOrEmpty(engine))
            {
                MessageBox.Show("没有空闲的引擎，无法启动", "提示");
                return;
            }

            Device currDevice;
            string deviceId = getCurrDeviceId();

            if ( DeviceStatus.ContainsKey(deviceId))
            {
                currDevice = DeviceStatus[deviceId];
                int s = currDevice.getStatus();
                if ( s == 1 || s == 2 )
                {
                    MessageBox.Show("程序已运行不能重复运行", "提示");
                    return;
                }
            }  




            if (string.IsNullOrEmpty(deviceId))
            {
                MessageBox.Show("设备Id不能为空", "提示");
                return;
            }

            DataTable gkdt = DataBaseManager.GetInstance.getDataChooseChallenge(deviceId);

            if (gkdt.Rows.Count == 0)
            {
                MessageBox.Show("挑战关卡不能为空，请选择要挑战的关卡", "提示");
                return;
            }

            DataTable dt = DataBaseManager.GetInstance.getGameStatus(deviceId);

            if (dt.Rows.Count == 0)
            {
                DataBaseManager.GetInstance.AddGameStatusRecord(deviceId, 1, engine);
            }
            else
            {
                DataBaseManager.GetInstance.UpdateGameStatusRecord(deviceId, 1, engine);
            }

 
           bool isStart = this.StartGameTool(engine, deviceId);
            if (isStart)
            {
                if (DeviceStatus.ContainsKey(deviceId))
                {
                    currDevice = DeviceStatus[deviceId];
                    currDevice.setStatus(1);
                }
               
                EngineStatus[engine] = 1;
                MessageBox.Show("启动成功", "提示");
            }
            else
            {
                MessageBox.Show("启动失败", "提示");
            }


            

        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            int i = 1;
            foreach (Device row in DeviceStatus.Values)
            {
                DataTable data = DataBaseManager.GetInstance.getGameStatus(row.getId());



                if (data.Rows.Count == 0)
                {
                    continue;
                }
                DataRow[] dr = data.Select();

                string heartbeat = dr[0][3].ToString();
                string engine = dr[0][2].ToString();
                DateTimeOffset dateTimeOffset;
                if (DateTimeOffset.TryParse(heartbeat, out dateTimeOffset))
                {

                    TimeSpan timeSpan = DateTimeOffset.Now - dateTimeOffset;
                    if (timeSpan.TotalSeconds < 20)
                    {
                        row.setStatus(1);
                        DeviceStatus[row.getId()] = row;
                        EngineStatus[engine] = 1;
                    }
                    else
                    {
                        row.setStatus(3);
                        DeviceStatus[row.getId()] = row;
                        EngineStatus[engine] = 0;
                    };
                }
                else
                {
                    Console.WriteLine("转换失败");
                }

                string status = string.Format("{0}:{1}", row.getId(), row.getStatusDisply());

                switch (i)
                {
                    case 1:
                        toolStripStatusLabel1.Text = status;
                        break;
                    case 2:
                        toolStripStatusLabel2.Text = status;
                        break;

                    case 3:
                        toolStripStatusLabel3.Text = status;
                        break;
                    case 4:
                        toolStripStatusLabel4.Text = status;
                        break;
                    case 5:
                        toolStripStatusLabel5.Text = status;
                        break;
                }
                i++;
            }


        }

        private void button11_Click(object sender, EventArgs e)
        {
            string deviceId = getCurrDeviceId();

            if (string.IsNullOrEmpty(deviceId))
            {
                MessageBox.Show("设备Id不能为空", "提示");
                return;
            }

            DataBaseManager.GetInstance.UpdateGameStatusRecord(deviceId, 3, "");

        }

        private void btnKillEngine_Click(object sender, EventArgs e)
        {
            DialogResult result = MessageBox.Show("你确定要执行这个操作吗？", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (result == DialogResult.Yes)
            {
                // 用户点击了“是”  
                this.KillGameTool();
            }

        }

        private void dgvDevice_RowDividerDoubleClick(object sender, DataGridViewRowDividerDoubleClickEventArgs e)
        {
            this.loadData();
            label3.Text = string.Format("在这里设置设备：{0} 相关参数！", getCurrDeviceId());
        }

        private void dgvDevice_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            this.loadData();
            label3.Text = string.Format("在这里设置设备：{0} 相关参数！", getCurrDeviceId());
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string deviceId = getCurrDeviceId();

            if (string.IsNullOrEmpty(deviceId))
            {
                MessageBox.Show("设备Id不能为空", "提示");
                return;
            }


            DataBaseManager.GetInstance.UpdateGameGkRecord(deviceId, ckb_zxtz.Checked, ckb_tbxd.Checked, ckb_tbxd.Checked);
        }

        private void btnCut_Click(object sender, EventArgs e)
        {
            string deviceId = getCurrDeviceId();


            if (string.IsNullOrEmpty(deviceId))
            {
                MessageBox.Show("设备Id不能为空", "提示");
                return;
            }

            this.CutTool(deviceId);
        }

        private void btnAddGk_Click(object sender, EventArgs e)
        {
            string deviceId = getCurrDeviceId();


            if (string.IsNullOrEmpty(deviceId))
            {
                MessageBox.Show("设备Id不能为空", "提示");
                return;
            }
            SkillForm skillForm = new SkillForm(2, deviceId);
            skillForm.ShowDialog();
        }
    }

    class Device
    {
        public Device(string id)
        {
            _id = id;
        }
        private string _id;
        private int _status;
        private string _engine;

        public string getId()
        {
            return _id;
        }

        public void setId(string id)
        {
            _id = id;
        }

        public int getStatus()
        {
            return _status;
        }

        public string getStatusDisply()
        {
            switch (_status)
            {
                case 0:
                    return "未运行";
                case 1:
                    return "运行中";
                case 2:
                    return "暂停中";
                case 3:
                    return "已退出";
                default:
                    return "未运行";
            }
        }
        public void setStatus(int status)
        {
            _status = status;
        }

        public string getEngine()
        {
            return _engine;
        }
        public void getEngine(string engine)
        {
            _engine = engine;
        }
    }
}